"""
Case Type   : 服务端工具
Case Name   : 验证gs_om工具功能
Create At   : 2024.10.8
Owner       : wang-tianjing1
Description :
    1.显示帮助信息
    2.显示版本号信息
    3.查询数据库状态
    3.停止数据库
    5.启动数据库
    6.查询数据库详细状态信息
    7.查看静态配置
    8.生成静态配置文件
Expect      :
    1.显示正确
    2.显示正确
    3.成功
    4.成功
    5.成功
    6.成功
    7.成功
    8.成功
History     :
"""
import unittest
import os
from yat.test import Node
from yat.test import macro
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.primary_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.commonsh = CommonSH()
        self.static_file_path = os.path.join(
            os.path.dirname(macro.DB_INSTANCE_PATH), 'tool', 'script',
            'static_config_files')

    def test_server_tools1(self):
        self.log.info('-------step1:显示帮助信息;except:显示正确--------')
        cmd_list = ['-?', '--help']
        for cmd in cmd_list:
            check_cmd1 = f'''source {macro.DB_ENV_PATH}
                gs_om {cmd}'''
            self.log.info(check_cmd1)
            msg1 = self.primary_node.sh(check_cmd1).result()
            self.log.info(msg1)

            self.log.info(
                '--------------从OLAP scene:开始截取msg1-------------------')
            self.log.info(
                '-------截取OLAP scene到General options部分的语法--------')
            start_index1 = msg1.find('OLAP scene:') + len('OLAP scene:')
            start_index2 = msg1.find('General options:')
            temp = msg1[start_index1:start_index2].split('\n')
            options_list1 = []
            for j in temp[1:-2]:
                options_list1.append(j.strip())
            else:
                pass
            self.log.info(options_list1)
            grammar = [
                'gs_om -t start [-h HOSTNAME] [-D dataDir] \
                [--time-out=SECS] [--security-mode=MODE] [-l LOGFILE]',
                'gs_om -t stop [-h HOSTNAME] [-D dataDir] [--time-out=SECS] \
                [-m MODE] [-l LOGFILE]',
                'gs_om -t status [-h HOSTNAME] [-o OUTPUT] [--detail] \
                [--all] [-l LOGFILE]',
                'gs_om -t generateconf -X XMLFILE [--distribute] [-l LOGFILE]',
                'gs_om -t cert [--cert-file=CERTFILE | --rollback] [-L] \
                [-l LOGFILE]',
                'gs_om -t kerberos -m [install|uninstall] -U USER \
                 [-l LOGFILE]',
                '[--krb-server|--krb-client]',
                'gs_om -t view [-o OUTPUT]',
                'gs_om -t query [-o OUTPUT]',
                'gs_om -t refreshconf']
            if len(options_list1) == len(grammar):
                for opt in options_list1:
                    if opt in grammar:
                        self.log.info(f'{opt}----语法校验通过----')
                    else:
                        self.log.error(f'{opt}----语法校验不通过----')
            else:
                self.log.error('---------语法校验有误---------')

            self.log.info('--定义一个空的列表，将获取的参数写入这个列表，并打印出该列表--')
            options_list2 = []
            for i in msg1[start_index2:].split('\n'):
                for j in i.split(' '):
                    if len(j) != 0:
                        if j[0] == '-':
                            options_list2.append(j)
                        else:
                            pass
                    else:
                        pass
            self.log.info(options_list2)
            parameter = [
                '-t', '-l', '-?,', '--help', '-V,', '--version',
                '-h', '-D', '--time-out=SECS',
                '--security-mode=MODE', '-h', '-m,', '--mode=MODE',
                '-D', '--time-out=SECS',
                '-h', '--az', '-o', '--detail', '--all', '-X',
                '--distribute', '--cert-file',
                '--rollback', '-L', '-m', '-U', '--krb-server',
                '--krb-client']
            if len(options_list2) == len(parameter):
                for opt in options_list2:
                    if opt in parameter:
                        self.log.info(f'{opt}-------参数校验通过--------')
                    else:
                        self.log.error(f'{opt}------参数校验不通过------')
            else:
                self.log.error('---------参数校验有误---------')

        self.log.info('--------step2:显示版本号信息;except:显示正确---------')
        cmd_list = ['-V', '--version']
        for cmd in cmd_list:
            check_cmd1 = f'''source {macro.DB_ENV_PATH}
                gs_om {cmd}'''
            self.log.info(check_cmd1)
            msg1 = self.primary_node.sh(check_cmd1).result()
            self.log.info(msg1)
            self.assertIn('openGauss', msg1)

        self.log.info('-------step3:查询数据库状态;except:成功---------')
        status_cmd1 = f'source {macro.DB_ENV_PATH}; gs_om -t status;'
        self.log.info(status_cmd1)
        status_msg1 = self.primary_node.sh(status_cmd1).result()
        self.log.info(status_msg1)
        self.assertTrue("Degraded" in status_msg1 or "Normal" in status_msg1)

        self.log.info('---------step4:停止数据库;except:成功------------------')
        certificate_path = os.path.join(macro.DB_INSTANCE_PATH, 'server.*')
        ls_cmd = f"ls -l {certificate_path}"
        self.log.info(ls_cmd)
        stop_cmd = self.commonsh.stop_db_cluster()
        self.log.info(stop_cmd)
        self.assertTrue(stop_cmd)

        self.log.info('--------step5:启动数据库;except:成功------------------')
        start_cmd = self.commonsh.start_db_cluster()
        self.log.info(start_cmd)
        self.assertTrue(start_cmd)

        self.log.info('-------step6:查询数据库详细状态信息;except:成功----------')
        query_cmd = f'source {macro.DB_ENV_PATH};gs_om -t query;'
        self.log.info(query_cmd)
        query_msg = self.primary_node.sh(query_cmd).result()
        self.log.info(query_msg)
        self.assertTrue("Degraded" in query_msg or "Normal" in query_msg)

        self.log.info('---------step7:查看静态配置;except:成功------------------')
        check_cmd2 = f'''source {macro.DB_ENV_PATH};
            gs_om -t view;
            '''
        self.log.info(check_cmd2)
        msg2 = self.primary_node.sh(check_cmd2).result()
        self.log.info(msg2)
        self.log.info('---------从数据库状态信息中获取节点数量----------')
        db_status = self.commonsh.get_db_cluster_status('detail')
        if db_status.count('|') > 0:
            dest_str = db_status.splitlines()[-1].strip()
            self.log.info(dest_str)
            dest_list = dest_str.split('|')
            self.log.info(dest_list)
            node_num = len(dest_list)
            self.log.info(node_num)
        else:
            dest_str = db_status.splitlines()[-1].strip()
            self.log.info(dest_str)
            node_num = int(dest_str[0].strip())
            self.log.info(node_num)
        self.log.info('----------从静态配置文件中获取节点数量-----------')
        msg2_list = msg2.splitlines()
        self.log.info(msg2_list)
        nodecount = ''
        for i in msg2_list:
            if 'nodeCount' in i:
                nodecount = i
                break
        count = int(nodecount.split(':')[1])
        self.log.info(count)
        if node_num == count:
            self.log.info('---------------静态配置检查正常-----------')
        else:
            raise Exception('静态配置异常')

        text = '-----step8:生成静态配置文件;except:成功------'
        self.log.info(text)
        generateconf_cmd = f'source {macro.DB_ENV_PATH};' \
                f'gs_om' \
                f' -t generateconf' \
                f' -X {macro.DB_XML_PATH}' \
                f' --distribute;'
        self.log.info(generateconf_cmd)
        generateconf_msg = self.primary_node.sh(generateconf_cmd).result()
        self.log.info(generateconf_msg)
        self.assertIn('static_config_files', generateconf_msg, '执行失败' + text)

        text = '--------检查生成的静态配置文件-------'
        self.log.info(text)
        check_cmd = f'source {macro.DB_ENV_PATH};ls {self.static_file_path};'
        self.log.info(check_cmd)
        check_msg = self.primary_node.sh(check_cmd).result()
        self.log.info(check_msg)
        self.assertIn('cluster_static_config', check_msg, '执行失败' + text)

    def tearDown(self):
        self.log.info('--------------无需清理环境-------------------')
        self.log.info(f'-----{os.path.basename(__file__)} end------')
